package com.uit.trip_.tab_activity;

import java.util.ArrayList;
import java.util.List;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.uit.trip_.R;
import com.uit.trip_.TripApplication;
import com.uit.trip_.bridge.Parser;
import com.uit.trip_.bridge.Server;
import com.uit.trip_.location.MyItemizedOverlay;
import com.uit.trip_.location.MyLocation;
import com.uit.trip_.models.Trip;

import android.R.bool;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.Toast;

public class Tab_TripLocationActivity extends MapActivity {

	private MapView mapView;
	private MapController mapController;
	private LocationManager locationManager;
	private List<Overlay> mapOverlays;
	private List<Trip> tripListLocations;
	private BroadCastLocations locationReceiver;
	public static final String NEW_LIST_LOCATIONS = "newlistlocations";
	private Server server;
	private Location _location;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.tab_location);

		server = new Server(this);
		tripListLocations = new ArrayList<Trip>();
		locationReceiver = new BroadCastLocations();
		mapView = (MapView) findViewById(R.id.mymap);
		mapOverlays = mapView.getOverlays();
		mapController = mapView.getController();

		mapView.setBuiltInZoomControls(true);

		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		_location = locationManager
				.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		updateWithNewLocation(_location);
		locationManager.requestLocationUpdates(
				LocationManager.NETWORK_PROVIDER, 300000, 10, listener);
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		unregisterReceiver(locationReceiver);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case 0:
			Toast.makeText(this, "Refresh", Toast.LENGTH_SHORT).show();
			_location = locationManager
					.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
			updateWithNewLocation(_location);
			break;

		default:
			break;
		}
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0, 0, 0, "Refresh");
		return true;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		registerReceiver(locationReceiver, new IntentFilter(NEW_LIST_LOCATIONS));
		TripApplication app = (TripApplication) getApplication();

		if (app.getUser() != null && tripListLocations.size() == 0) {
			getListLocations(_location);
		}
	}

	/*
	 * Update lai vi tri khi co thay doi xay ra
	 */
	private void updateWithNewLocation(Location location) {

		mapController.setZoom(15);
		// Delete all things which on the map
		mapOverlays.clear();
		// Update the new location
		if (location != null) {

			Drawable resources = getResources().getDrawable(
					R.drawable.tab_location);

			// Draw your location to the map
			// 1-Translate the location to the geo
			Double la = location.getLatitude() * 1E6;
			Double lng = location.getLongitude() * 1E6;
			GeoPoint geo = new GeoPoint(la.intValue(), lng.intValue());
			// 2-Go to the center point
			mapController.animateTo(geo);
			// -3
			OverlayItem overlayItem = new OverlayItem(geo, "You are here", "");
			MyLocation myLocation = new MyLocation(resources, geo, mapView);
			myLocation.addOverlay(overlayItem);
			// -4 Add to the overlays
			mapOverlays.add(myLocation);

			getListLocations(location);
		}

	}

	private void getListLocations(Location location) {
		TripApplication app = (TripApplication) getApplication();
		if (app.getUser() != null) {
			server.getListLocations(Double.toString(location.getLatitude()),
					Double.toString(location.getLongitude()),
					app.getUser().userId);
		}
	}

	private LocationListener listener = new LocationListener() {

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub

		}

		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub

		}

		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub

		}

		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub
			_location = location;
			updateWithNewLocation(location);
		}
	};

	private void drawTripListToMap(List<Trip> tripList) {
		// Log.i("duongnx", "drawTripListToMap" + tripList.size());
		for (int i = 0; i < tripList.size(); i++) {
			Trip trip = tripList.get(i);
			if (trip.la != null && trip.lng != null) {
				Double la = Double.parseDouble(trip.la) * 1E6;
				Double lng = Double.parseDouble(trip.lng) * 1E6;
				GeoPoint geoPoint = new GeoPoint(la.intValue(), lng.intValue());

				OverlayItem overlayItem = new OverlayItem(geoPoint,
						trip.userName, trip.time);
				MyItemizedOverlay myItemizedOverlay = new MyItemizedOverlay(
						getResources().getDrawable(R.drawable.mark), mapView,
						trip);
				myItemizedOverlay.addOverlay(overlayItem);
				mapOverlays.add(myItemizedOverlay);
				if (i == 0) {
					mapController.animateTo(geoPoint);
				}
			}
		}
	}

	private class BroadCastLocations extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			Log.i("duongnx", "BroadCastLocations");
			Bundle extras = intent.getExtras();
			if (extras == null) {
				return;
			}

			boolean result = extras.getBoolean("result");
			if (result) {
				String response = extras.getString("response");
				Log.i("duongnx", "getListLofcation:" + response);
				tripListLocations = Parser.parseImageList(response);
				Log.i("duongnx", "trip size:" + tripListLocations.size());
				if (tripListLocations.size() > 0) {
					// TripApplication app = (TripApplication) getApplication();
					// app.setTripList(tripListLocations,
					// TripApplication.TYPE_LOCATION);
					drawTripListToMap(tripListLocations);
				} else {
					Toast.makeText(getApplicationContext(), "No trip found",
							Toast.LENGTH_SHORT).show();
				}
			} else {
				Log.i("duongnx", "getlistlocation fail");
				Toast.makeText(getApplicationContext(), "Get trip list fail",
						Toast.LENGTH_SHORT).show();
			}
		}

	}
}